
let questions = [];


async function fetchQuestions() {
    try {
        const response = await fetch('/examination/addsubject-CS');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        // 假设 questions 是这个函数外部的一个变量，你可能需要将其声明为全局变量或模块级别的变量
        questions = data;
        renderQuestions();
    } catch (error) {
        console.error('Error fetching questions:', error);
    }
}

// 渲染问题的函数  
function renderQuestions() {
    const questionsContainer = document.getElementById('questions');
    questions.forEach((item, index) => {
        const questionDiv = document.createElement('div');
        questionDiv.classList.add('question');

        if (item.type === "objective") {
            let optionsHtml = "";
            item.options.forEach((option, i) => {
                optionsHtml += `<input type="radio" id="option${index}-${i}" name="question${index}" value="${option}"> <label for="option${index}-${i}">${option}</label><br>`;
            });
            questionDiv.innerHTML = `<p>${item.question}</p>${optionsHtml}`;
        } else if (item.type === "subjective") {
            questionDiv.innerHTML = `<p>${item.question}</p> <input type="text" id="answer${index}" placeholder="Your Answer">`;
        }
        questionsContainer.appendChild(questionDiv);
    });


    document.getElementById('submitBtn').addEventListener('click', () => {
        let answers = [];

        // 遍历问题数组  
        questions.forEach((item, index) => {
            let answer = null;

            if (item.type === "objective") {
                const selectedOption = document.querySelector(`input[name="question${index}"]:checked`);
                if (selectedOption) {
                    answer = selectedOption.id.split('-')[1];
                    if (answer !== null) {
                        answers.push({
                            objective: answer,
                        });
                    }
                }
            } else if (item.type === "subjective") {
                const userAnswer = document.getElementById(`answer${index}`).value.trim();
                answer = userAnswer;
                if (answer !== null) {
                    answers.push({
                        subjective: answer,
                    });
                }
            }
        });

        // 使用fetch API发送POST请求  
        fetch('/examination/answer', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ answers: answers }),
        })
            .then(response => {
                // 检查响应是否成功  
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json(); // 解析JSON（如果服务器返回JSON）  
            })
            .then(data => {
                // 处理从服务器返回的数据  
                console.log('Success:', data);
                alert("提交成功");
                window.location.href = "student.html";
            })
            .catch(error => {
                // 捕获并处理任何错误  
                console.error('Error:', error);
            });
    });
}

// 页面加载完成后调用fetchQuestions函数  
document.addEventListener('DOMContentLoaded', fetchQuestions);